﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

using Rio.Flow.Application.Models.Flow;

using Telerik.Windows.Controls;
using Rio.Framework.Pages.Workflow.Models;

namespace Rio.Framework.Pages.Workflow
{
    public partial class FlowPanelBarItem : RadPanelBarItem
    {
        #region Fields

        private bool doubleClickFlag;
        private DispatcherTimer doubleClickTimer = new DispatcherTimer();
        private long numberOfNewItemsInFolderType;
        private FlowTreeModel _flowTreeModel;

        #endregion Fields

        #region Constructors

        public FlowPanelBarItem()
        {
            InitializeComponent();

            this.Name = Guid.NewGuid().ToString();

            this.doubleClickTimer.Interval = TimeSpan.FromMilliseconds(200);
            this.doubleClickTimer.Tick += doubleClickTimer_Tick;
        }

        #endregion Constructors

        #region Delegates

        public delegate void FlowPanelBarItemEventhandler(object sender, DataItemTreeView selectedItem);

        #endregion Delegates

        #region Events

        public event FlowPanelBarItemEventhandler ItemSelected;

        #endregion Events

        #region Properties

        public FlowTreeModel FlowTreeModel
        {
            get { return _flowTreeModel; }
            set
            {
                _flowTreeModel = value;
            }
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// Loads the structure.
        /// </summary>
        public void LoadStructure()
        {
            TreeView.Items.Clear();

            numberOfNewItemsInFolderType = 0;

            foreach (var item in FlowTreeModel.Items.OrderBy(i => i.Key.Label))
            {
                RadTreeViewItem treeViewItem = new RadTreeViewItem();

                treeViewItem.AddHandler(RadTreeViewItem.MouseLeftButtonUpEvent, new MouseButtonEventHandler(TreeViewItem_Selected), true);

                TextBlock headerTextBlock = new TextBlock()
                {
                    Text = item.Key.Label
                };

                if (item.Value.Any(i => i.bIsExpanded))
                {
                    long numberOfNewItems = ( from i in item.Value select i.NumberNewItem ).Sum();

                    headerTextBlock.Text += String.Format("({0})", numberOfNewItems);

                    numberOfNewItemsInFolderType += numberOfNewItems;

                    treeViewItem.IsExpanded = true;
                }
                else
                {
                    treeViewItem.IsExpanded = false;
                }

                treeViewItem.Header = headerTextBlock;
                treeViewItem.DefaultImageSrc = new BitmapImage(new Uri("../Assets/Images/FolderType.png", UriKind.Relative));

                treeViewItem.ItemsSource = item.Value;
                treeViewItem.ItemTemplate = this.Resources["TreeViewItemTemplate"] as Telerik.Windows.Controls.HierarchicalDataTemplate;

                TreeView.Items.Add(treeViewItem);
            }

            HeaderTextBlock.Text = FlowTreeModel.Organization.Name;

            if (numberOfNewItemsInFolderType > 0)
            {
                HeaderTextBlock.Text += String.Format("({0})", numberOfNewItemsInFolderType);

                IsExpanded = true;
            }
            else
            {
                IsExpanded = false;
            }
        }

        /// <summary>
        /// Called when [item selected].
        /// </summary>
        /// <param name="selectedItem">The selected item.</param>
        protected void OnItemSelected(DataItemTreeView selectedItem)
        {
            if (this.ItemSelected != null)
            {
                ItemSelected(this, selectedItem);
            }
        }

        /// <summary>
        /// Handles the Tick event of the doubleClickTimer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void doubleClickTimer_Tick(object sender, EventArgs e)
        {
            this.doubleClickTimer.Stop();
            this.doubleClickFlag = false;
        }

        /// <summary>
        /// Handles the Selected event of the treeViewItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Telerik.Windows.RadRoutedEventArgs"/> instance containing the event data.</param>
        private void TreeViewItem_Selected(object sender, MouseButtonEventArgs e)
        {
            if ((RadTreeView)((RadTreeViewItem)sender).Parent != null
                && (((RadTreeView)((RadTreeViewItem)sender).Parent).SelectedItem as DataItemTreeView) != null
                && (((RadTreeView)((RadTreeViewItem)sender).Parent).SelectedItem as DataItemTreeView).ItemType != WorkflowTreeItemType.None
                && (((RadTreeView)((RadTreeViewItem)sender).Parent).SelectedItem as DataItemTreeView).SubItemType != WorkflowTreeSubItemType.None)
            {
                    OnItemSelected(((RadTreeView)((RadTreeViewItem)sender).Parent).SelectedItem as DataItemTreeView);
            }
        }

        #endregion Methods
    }
}